package com.zerowidth.moc.web.pay.wx;

import com.zerowidth.db.utils.StringUtils;
import com.zerowidth.moc.web.utils.GsonUtils;
import com.zerowidth.moc.web.utils.LogUtil;

import java.io.IOException;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class WXOrderFactory {

    private static final String URL_CREATE_ORDER = "https://api.mch.weixin.qq.com/pay/unifiedorder";

    private static final String APP_ID = "wx472af8d4de2fb0ff";

    //商户号； 商户简称：武汉青回网络科技有限公司
    private static final String MCH_ID = "1664150596";

    //商户平台设置的 APIv2密钥
    public static final String PARTER_KEY = "38DB173FE2E97E25C5893F5AAF905454";

    private static String MY_SERVER_IP = "116.62.121.194";

    /**
     * 创建APP支付订单
     */
    public static Map<String, String> createAPPOrderInfo(String body, String subject, String outTradeNo, String timeOutExpress,
                                                         int amountFen, String productCode, String notifyUrl) {

        TreeMap<String, String> params = new TreeMap<>();
        params.put("appid", APP_ID);
        params.put("mch_id", MCH_ID);
        params.put("device_info", "WEB"); // 默认 "WEB"
        String nonce_str = WXUtil.getRandomStr();
        params.put("nonce_str", nonce_str);
        params.put("body", subject);
        params.put("attach", "");
        params.put("out_trade_no", outTradeNo);
        //微信订单的总金额，单位为：分，1元钱=100分钱
        params.put("total_fee", amountFen + "");
        params.put("spbill_create_ip", MY_SERVER_IP);
        params.put("notify_url", notifyUrl);
        params.put("trade_type", "APP");
        // 生成数字签名
        String sign = WXUtil.createSign(params, PARTER_KEY);
        params.put("sign", sign);


        String result = null; // 执行 HTTP 请求，获取接收的字符串（一段 XML）
        try {
            result = WXUtil.executeHttpPost(URL_CREATE_ORDER, params);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            Map<String, String> map = WXUtil.createSign2(result, PARTER_KEY);

            if (map.get("return_code") != null) {
                System.out.println(map.get("return_msg"));
                return null;
            }
            return map;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 创建二维码支付
     */
    public static Map<String, String> createQrCodeOrderInfo(String subject, String outTradeNo,
                                                            String notifyUrl, int amountFen) {

        TreeMap<String, String> params = new TreeMap<>();
        params.put("appid", APP_ID);
        params.put("mch_id", MCH_ID);
        String nonce_str = WXUtil.getRandomStr();
        params.put("nonce_str", nonce_str);
        params.put("body", subject);
        params.put("attach", "");
        params.put("out_trade_no", outTradeNo);
        params.put("total_fee", amountFen + "");//微信订单的总金额，单位为：分，1元钱=100分钱
        params.put("spbill_create_ip", MY_SERVER_IP);
        params.put("notify_url", notifyUrl);
        params.put("trade_type", "NATIVE");
        // 生成数字签名
        String sign = WXUtil.createSign(params, PARTER_KEY);
        params.put("sign", sign);

        try {
            String result = WXUtil.executeHttpPost(URL_CREATE_ORDER, params);
            SortedMap<String, String> responseMap = new TreeMap<>(XmlUtils.transferXmlToMap(result));

            LogUtil.e("wx_qrcode", GsonUtils.toJsonString(responseMap));

            String signOuter = responseMap.remove("sign");
            String signInner = WXUtil.createSign(responseMap, PARTER_KEY);
            if (!StringUtils.equals(signOuter, signInner)) {
                //签名校验不通过
                return null;
            }

            if (StringUtils.equals(responseMap.get("return_code"), "SUCCESS")) {
                return responseMap;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

}